package com.example.administrator.liveapp;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.example.administrator.liveapp.Xutils3.MyCallBack;
import com.example.administrator.liveapp.Xutils3.XUtils;
import com.example.administrator.liveapp.activity.EditActivity;
import com.example.administrator.liveapp.activity.LoginPage;
import com.example.administrator.liveapp.activity.WxLoginPage;
import com.example.administrator.liveapp.base.BaseFragment;
import com.example.administrator.liveapp.bean.LoginBean;
import com.example.administrator.liveapp.fragment.FoundFragment;
import com.example.administrator.liveapp.fragment.LiveFragment;
import com.example.administrator.liveapp.fragment.LiveManFragment;
import com.example.administrator.liveapp.fragment.MainFragment;
import com.example.administrator.liveapp.fragment.MallFragment;
import com.example.administrator.liveapp.fragment.MyFragment;
import com.example.administrator.liveapp.utils.AppUrl;
import com.example.administrator.liveapp.utils.SharedPrefsUtil;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.util.LogUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    public RadioGroup rg_bottom_tag;
    public List<BaseFragment> mBaseFragments;
    /**
     * RadioGroup切换Fragment所对应的位置
     */
    public int position;

    /**
     *上次切换的Fragment
     */
    public Fragment mContent;

    /**
     * 登录用户手机号
     */
    public String phone;

    /**
     *登录用户密码
     */
    public String passwords;
    /**
     * 微信openid
     */
    public String openid;
    public String unionid;
    public String screen_name;
    public String iconurl;
    public SharedPrefsUtil sp;
    public ApplicationUtils applicationUtils;
    private LoginBean loginBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        applicationUtils = new ApplicationUtils();
        applicationUtils.addActivity(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("action.refreshFriend");
        registerReceiver(mRefreshBroadcastReceiver, intentFilter);
        initView();
        setData();
        initFragment();
        setListener();
    }

    private BroadcastReceiver mRefreshBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals("action.refreshFriend"))
            {
                setData();
            }
        }
    };

    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mRefreshBroadcastReceiver);
    }

    private long firstTime = 0;
    /**
     * 双击返回键推出app
     */
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            long secondTime = System.currentTimeMillis();
            if (secondTime - firstTime > 2000) {
                Toast.makeText(MainActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                firstTime = secondTime;
                return true;
            } else {
                applicationUtils.onTerminate();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private void setData() {
        sp = new SharedPrefsUtil();
        phone = sp.getStringValue(MainActivity.this,"username",null);
        passwords = sp.getStringValue(MainActivity.this,"userpassword",null);
        openid = sp.getStringValue(MainActivity.this,"openid",null);
        unionid = sp.getStringValue(MainActivity.this,"unionid",null);
        screen_name = sp.getStringValue(MainActivity.this,"screen_name",null);
        iconurl = sp.getStringValue(MainActivity.this,"iconurl",null);
        if(phone!=null&&passwords!=null||openid!=null) {
            String url = AppUrl.URLS + AppUrl.LoginURL;
            Map<String, String> map = new HashMap<>();
            if(phone!=null&&passwords!=null){
                map.put("consumerTel", phone);
                map.put("pass", passwords);
            }else{
                map.put("openid", openid);
                map.put("unionid",unionid);
                map.put("screen_name",screen_name);
                map.put("iconurl",iconurl);
                map.put("tid", "1");
            }
            XUtils.Get(url, map, new MyCallBack<String>() {
                @Override
                public void onSuccess(String result) {
                    super.onSuccess(result);
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        String code = jsonObject.optString("code");
                        if (code.equals("4200")) {
                            Gson gson = new Gson();
                            loginBean = gson.fromJson(result, LoginBean.class);
                            ApplicationUtils.getInstance().loginBean = loginBean;
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    super.onError(ex, isOnCallback);
                    LogUtil.e(ex.getMessage() + "联网请求失败");
                }
            });
        }
    }


    private void setListener() {
        rg_bottom_tag.setOnCheckedChangeListener(new MyOnCheckedChangeListener());
        //设置默认主页面
        rg_bottom_tag.check(R.id.rb_found);
    }

    class MyOnCheckedChangeListener implements RadioGroup.OnCheckedChangeListener {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId){
                case R.id.rb_found:
                    position = 0;
                    break;
                case R.id.rb_live:
                    position = 1;
                    break;
                case R.id.rb_mall:
                    position = 2;
                    break;
                case R.id.rb_my:
                    position = 3;
                    break;
                default:
                    position = 0;
                    break;
            }

            Fragment fragment = getFragment();
            switchFragment(mContent, fragment);

        }
    }

    /**
     * 得到Fragment
     * @return
     */
    private BaseFragment getFragment() {
        if(mBaseFragments != null){
            BaseFragment baseFragment = mBaseFragments.get(position);
            return baseFragment;
        }
        return null;
    }

    /**
     * 切换不同的Fragment
     * @param from
     * @param to
     */
    public void switchFragment(Fragment from, Fragment to) {

        if (mContent != to) {
            mContent = to;
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            if (!to.isAdded()) {
                // 先判断是否被add过
                if(from != null){
                    transaction.hide(from);
                }
                if(to != null){
                    transaction.add(R.id.fl_content, to).commit();
                }

            } else {
                if(from != null){
                    transaction.hide(from);
                }
                if(to != null){
                    transaction.show(to).commit();
                }
            }
        }
    }


    /**
     * 初始化Fragment
     */
    private void initFragment(){
        mBaseFragments = new ArrayList<>();
        mBaseFragments.add(new MainFragment());//发现
        mBaseFragments.add(new LiveManFragment());//直播
        mBaseFragments.add(new MallFragment());//商城
        mBaseFragments.add(new MyFragment());//我的
    }

    @Override
    public void onBackPressed() {
        Intent i = new Intent(Intent.ACTION_MAIN);
        // i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //如果是服务里调用，必须加入new task标识
        i.addCategory(Intent.CATEGORY_HOME);
        startActivity(i);
    }

    private void initView() {
        rg_bottom_tag = (RadioGroup) findViewById(R.id.rg_bottom_tag);
        findViewById(R.id.add_article).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(ApplicationUtils.getInstance().loginBean!=null){
                    Intent intent = new Intent(MainActivity.this, EditActivity.class);
                    startActivity(intent);
                    overridePendingTransition(R.anim.zoomin,R.anim.zoomout);
                }else{
                    startActivity(new Intent(MainActivity.this,WxLoginPage.class));
                    overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
                    Toast.makeText(MainActivity.this, "请先登录后添加文章", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}
